package com.lzw.breezeNovel.webApp.service.impl.novel;

import com.lzw.breezeNovel.common.exception.BaseException;
import com.lzw.breezeNovel.common.login.LoginUser;
import com.lzw.breezeNovel.common.login.LoginUserHolder;
import com.lzw.breezeNovel.model.entity.pojo.novel.Book;
import com.lzw.breezeNovel.model.entity.pojo.novel.BookSelf;
import com.lzw.breezeNovel.model.entity.pojo.novel.Chapter;
import com.lzw.breezeNovel.model.entity.pojo.user.UserInfo;
import com.lzw.breezeNovel.model.enums.novel.BookStatus;
import com.lzw.breezeNovel.webApp.mapper.novel.BookSelfMapper;
import com.lzw.breezeNovel.webApp.mapper.user.UserInfoMapper;
import com.lzw.breezeNovel.webApp.service.novel.BookSelfService;
import com.lzw.breezeNovel.webApp.vo.novel.BookVo;
import com.lzw.breezeNovel.webApp.vo.novel.ChapterVo;
import lombok.extern.slf4j.Slf4j;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 清风明月
 * @Package com.lzw.breezeNovel.webApp.service.novel.impl
 * @date 2025/3/2
 * @description 书架的服务实现类
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class BookSelfServiceImpl implements BookSelfService {

    /**
     * 注入mapper
     */
    @Autowired
    private BookSelfMapper bookSelfMapper;

    /**
     * 注入用户的mapper
     */
    @Autowired
    private UserInfoMapper userMapper;


    /**
     * 获取书架
     * @return
     */
    @Override
    @Transactional(readOnly = true)
    public List<BookVo> getBookSelf() {
        // 获取当前用户
        UserInfo userInfo = getUserInfo();
        // 进行分页查询
        List<BookSelf> bookSelves = bookSelfMapper.getBookSelfByPage(userInfo.getUserId());

        // 提前处理书籍状态转换，避免在流中重复计算
        Map<Book, String> bookStatusMap = new HashMap<>();
        for (BookSelf bookSelf : bookSelves) {
            Book book = bookSelf.getBooks();
            if (book != null) {
                String statusDesc = BookStatus.getDescByCode(book.getStatus());
                bookStatusMap.put(book, statusDesc);
            }
        }

        // 创建一个bookvo的集合
        return bookSelves.stream()
                .map(bookSelf -> convertToBookVo(bookSelf, bookStatusMap))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    /**
     * 根据书籍id获取书籍
     * @param bookSelf
     * @param bookStatusMap
     * @return
     */
    @Nullable
    private BookVo convertToBookVo(@NotNull BookSelf bookSelf, Map<Book, String> bookStatusMap) {
        Book book = bookSelf.getBooks();
        if (book == null) {
            return null;
        }
        BookVo bookVo = new BookVo();
        try {
            BeanUtils.copyProperties(book, bookVo);
        } catch (BeansException e) {
            handleCopyException(e);
            return null;
        }

        // 设置书籍状态
        bookVo.setStatus(bookStatusMap.get(book));

        // 获取章节列表并转换
        List<Chapter> chapters = book.getChapters();
        if (chapters != null && !chapters.isEmpty()) {
            List<ChapterVo> chapterVos = convertChaptersToVos(chapters);
            bookVo.setChapters(chapterVos);
            // 获取最新章节
            Chapter newChapter = chapters.stream()
                    .max(Comparator.comparing(Chapter::getChapterNumber))
                    .orElse(null);
            bookVo.setNewChapter(newChapter);
        }

        return bookVo;
    }

    /**
     * 将章节列表转换为章节Vo列表
     * @param chapters
     * @return
     */
    private List<ChapterVo> convertChaptersToVos(@NotNull List<Chapter> chapters) {
        return chapters.stream()
                .map(this::convertChapterToVo)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    /**
     * 将章节转换为章节Vo
     * @param chapter
     * @return
     */
    @Nullable
    private ChapterVo convertChapterToVo(Chapter chapter) {
        ChapterVo chapterVo = new ChapterVo();
        try {
            BeanUtils.copyProperties(chapter, chapterVo);
        } catch (BeansException e) {
            handleCopyException(e);
            return null;
        }
        return chapterVo;
    }

    /**
     * 处理对象拷贝异常
     * @param e
     */
    private void handleCopyException(BeansException e) {
        log.error("对象拷贝失败", e);
        throw new BaseException(500, "对象拷贝失败");
    }


    /**
     * 删除书架书籍
     * @param bookId
     */
    @Override
    public void deleteBook(Long bookId) {
        // 获取当前用户
        UserInfo userInfo = getUserInfo();
        bookSelfMapper.deleteBook(bookId, userInfo.getUserId());
    }

    /**
     * 添加书架书籍
     * @param bookId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBook(Long bookId) {
       // 获取当前用户
        UserInfo userInfo = getUserInfo();
        bookSelfMapper.addBook(bookId, userInfo.getUserId());
    }

    /**
     * 获取用户消息
     */
    @Transactional(readOnly = true)
    private UserInfo getUserInfo() {
        //获取当前用户
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        //获取当前
        String phone = loginUser.getPhone();
        return userMapper.selectByPhone(phone);
   }

}
